package com.onlinevideo.servlet;

import cn.hutool.json.JSONUtil;
import com.onlinevideo.data.ResultBean;
import com.onlinevideo.entity.History;
import com.onlinevideo.entity.User;
import com.onlinevideo.service.impl.HistoryServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class HistoryServlet extends BaseServlet {
    HistoryServiceImpl historyService = new HistoryServiceImpl();
    protected void showHistory(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = (User) req.getSession().getAttribute("user");
        PrintWriter writer = resp.getWriter();
        if (user == null) {
            writer.write(0);
        }
        List<History> histories = historyService.queryByUser(user.getId());
        String s = JSONUtil.toJsonStr(histories);
        writer.write(s);
    }
    protected void insertHistory(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = (User) req.getSession().getAttribute("user");
        String videoId = req.getParameter("videoId");
        PrintWriter writer = resp.getWriter();
        if (user == null) {
            return;
        }
        int insert = historyService.insert(new History(null, user.getId(), Long.valueOf(videoId), String.valueOf(System.currentTimeMillis())));
        writer.write(insert);
    }
    protected void deleteHistory(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = (User) req.getSession().getAttribute("user");
        int i = historyService.deleteByUserId(user.getId());
        if (i>0){
            resp.getWriter().write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess("删除历史成功")));
        }else {
            resp.getWriter().write(JSONUtil.toJsonStr(ResultBean.scOperationError("删除历史失败")));
        }
    }

}
